import { useEffect, useState } from 'react';

import { IoMdAdd } from 'react-icons/io';
import { ColumnDef } from '@tanstack/react-table';
import { useService } from '@flowgram.ai/free-layout-editor';

import { ChatModelType } from '@/typings/chatmodel';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';

import { Dialog, DialogContent, DialogHeader, DialogTitle } from '../../ui/dialog';
import { DataTable } from '../../ui/data-table';
import { CustomService } from '../../../services/custom-service';
import { LlmPropsSetting } from './llm-props';

export function LlmSetting({
  open,
  onOpenChange,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}) {
  const customService = useService(CustomService);
  const [loading, setLoading] = useState(false);
  const [selectedLlm, setSelectedLlm] = useState<ChatModelType | null>(null);
  const [llms, setLlms] = useState<ChatModelType[]>([]);
  const [resetTableTrigger, setResetTableTrigger] = useState(0);

  const columns: ColumnDef<ChatModelType>[] = [
    {
      accessorKey: 'ID',
      header: 'ID',
      enableResizing: false,
      size: 50,
    },
    {
      accessorKey: 'Name',
      header: '名称',
    },
  ];

  async function onDelete(row: ChatModelType) {
    console.log('onDelete', row);
    try {
      if (row.ID !== 0) {
        await customService.deleteModel(row.ID);
      }
      loadLlmList();
    } catch (e) {
      console.log('deleteFlow error', e);
    }
  }

  const onSelectedRowChange = (row: ChatModelType | null) => {
    console.log('onSelectedRowChange', row);
    setSelectedLlm(row);
  };

  const flowTable = (
    <div className="rounded-md border w-full">
      <DataTable
        columns={columns}
        data={llms}
        onDelete={onDelete}
        onSelectedRowsChange={onSelectedRowChange}
        resetTrigger={resetTableTrigger}
      />
    </div>
  );

  function loadLlmList() {
    const controller = new AbortController(); // Create abort controller
    setLoading(true);
    customService
      .getModelList(controller.signal)
      .then((res) => {
        setLlms(res);
      })
      .finally(() => {
        setLoading(false);
      });

    return () => {
      controller.abort();
    };
  }

  useEffect(() => {
    let cleanup: (() => void) | undefined;
    if (open) {
      cleanup = loadLlmList();
    }
    return () => cleanup?.();
  }, [open]);

  function onSaved() {
    setSelectedLlm(null);
    loadLlmList();
  }

  // 修改新增按钮点击事件
  const handleAddNew = () => {
    setResetTableTrigger((prev) => prev + 1); // 触发表格重置
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className={cn('w-[80vw] md:max-w-none max-h-[90vh]')}>
        <DialogHeader>
          <DialogTitle>大模型设置</DialogTitle>
        </DialogHeader>

        {/* 添加Flex布局容器 */}
        <div className="flex gap-4 mt-4">
          {/* 左侧表格区域 - 占比50% */}
          <div className="w-[280px] flex-shrink-0">
            {loading ? <div>Loading models...</div> : flowTable}
            <div className="flex justify-end">
              <Button
                className="mt-2 w-7 h-7 flex items-center justify-center py-1.5 text-sm"
                onClick={handleAddNew}
              >
                <IoMdAdd />
              </Button>
            </div>
          </div>
          {/* 右侧表单区域 - 占比50% */}
          <div className="flex-1 min-w-0">
            <LlmPropsSetting model={selectedLlm || undefined} onSaved={onSaved} />
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
